using UnityEngine;
using System.Collections.Generic;

public class ShellPool : MonoBehaviour
{
    public static ShellPool Instance;

    public GameObject shellPrefab;     // 子弹预制体
    public int poolSize = 20;          // 对象池大小

    private Queue<GameObject> poolQueue = new Queue<GameObject>();

    private void Awake()
    {
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);

        // 初始化对象池，生成的子弹全部设置为该对象的子物体
        for (int i = 0; i < poolSize; i++)
        {
            GameObject obj = Instantiate(shellPrefab);
            obj.SetActive(false);

            // 设置父物体为当前挂载脚本的物体
            obj.transform.SetParent(this.transform);

            poolQueue.Enqueue(obj);
        }
    }

    // 从池中取一个子弹
    public GameObject GetShell()
    {
        if (poolQueue.Count == 0)
        {
            GameObject obj = Instantiate(shellPrefab);
            obj.SetActive(false);
            obj.transform.SetParent(this.transform);
            poolQueue.Enqueue(obj);
        }

        GameObject shell = poolQueue.Dequeue();
        shell.SetActive(true);
        return shell;
    }

    // 将用完的子弹放回池中
    public void ReturnShell(GameObject shell)
    {
        shell.SetActive(false);
        shell.transform.SetParent(this.transform);  // 回收时确保父物体仍为池管理者
        poolQueue.Enqueue(shell);
    }
}
